package wei.xinya.springwebflux;

import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.netty.http.server.HttpServer;
import wei.xinya.springwebflux.handler.UserHandler;
import wei.xinya.springwebflux.service.UserServiceImpl;

import java.io.IOException;

import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.web.reactive.function.server.RequestPredicates.*;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler;

public class MyServer {

    public static void main(String[] args) throws IOException {
        MyServer myServer = new MyServer();
        myServer.createReactorServer();

        System.out.println("enter to exit");
        int read = System.in.read();
        if (read > 0) {
            System.out.println("exit!");
        }
    }

    public RouterFunction<ServerResponse> routerFunction() {
        UserServiceImpl userService = new UserServiceImpl();
        UserHandler userHandler = new UserHandler(userService);

        return route(GET("/user/{id}").and(accept(APPLICATION_JSON)), userHandler::getUserById)
                .andRoute(GET("/user").and(accept(APPLICATION_JSON)), userHandler::getAllUser)
                .andRoute(POST("/saveUser").and(accept(APPLICATION_JSON)), userHandler::saveUser);
    }

    public void createReactorServer() {
        RouterFunction<ServerResponse> route = routerFunction();
        HttpHandler httpHandler = toHttpHandler(route);
        ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler);

        HttpServer httpServer = HttpServer.create();
        httpServer.port(8090).handle(adapter).bindNow();
    }
}
